import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Eye, Clock, Trophy, Star, Target, Zap, CheckCircle, RotateCcw } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface VisualPerceptionTestProps {
  onComplete: (result: TestResult) => void;
}

interface VisualElement {
  id: number;
  x: number;
  y: number;
  width: number;
  height: number;
  color: string;
  shape: 'circle' | 'square' | 'triangle' | 'diamond' | 'star' | 'hexagon';
  rotation: number;
  opacity: number;
  isTarget: boolean;
  size: 'small' | 'medium' | 'large';
}

interface VisualTask {
  id: number;
  type: 'target_detection' | 'color_discrimination' | 'size_comparison' | 'spatial_memory' | 
        'shape_recognition' | 'pattern_matching';
  instruction: string;
  elements: VisualElement[];
  targets: number[];
  timeLimit: number;
  difficulty: 'easy' | 'medium' | 'hard';
  minTargets: number;
  maxTargets: number;
  showMemoryPhase?: boolean;
  memoryTime?: number;
}

export function VisualPerceptionTest({ onComplete }: VisualPerceptionTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'memory' | 'complete'>('instructions');
  const [currentTask, setCurrentTask] = useState(0);
  const [tasks, setTasks] = useState<VisualTask[]>([]);
  const [selectedElements, setSelectedElements] = useState<number[]>([]);
  const [responses, setResponses] = useState<{ correct: boolean; time: number; accuracy: number }[]>([]);
  const [timeLeft, setTimeLeft] = useState(0);
  const [taskStartTime, setTaskStartTime] = useState<number>(0);
  const [startTime, setStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [showFeedback, setShowFeedback] = useState(false);
  const [feedbackCorrect, setFeedbackCorrect] = useState(false);
  const [isMemoryPhase, setIsMemoryPhase] = useState(false);
  const [showCorrectAnswers, setShowCorrectAnswers] = useState(false);
  const canvasRef = useRef<HTMLCanvasElement>(null);

  const TOTAL_TASKS = 15;
  const CANVAS_WIDTH = 600;
  const CANVAS_HEIGHT = 400;

  // 颜色调色板
  const COLORS = [
    { name: '红色', hex: '#ef4444' },
    { name: '蓝色', hex: '#3b82f6' },
    { name: '绿色', hex: '#22c55e' },
    { name: '黄色', hex: '#f59e0b' },
    { name: '紫色', hex: '#8b5cf6' },
    { name: '橙色', hex: '#f97316' },
    { name: '粉色', hex: '#ec4899' },
    { name: '青色', hex: '#06b6d4' }
  ];

  // 生成随机视觉元素
  const generateRandomElement = useCallback((id: number, isTarget = false): VisualElement => {
    const shapes: VisualElement['shape'][] = ['circle', 'square', 'triangle', 'diamond', 'star', 'hexagon'];
    const sizes: VisualElement['size'][] = ['small', 'medium', 'large'];
    const sizeMap = { small: 25, medium: 35, large: 45 };
    
    const shape = shapes[Math.floor(Math.random() * shapes.length)];
    const size = sizes[Math.floor(Math.random() * sizes.length)];
    const actualSize = sizeMap[size];
    
    return {
      id,
      x: Math.random() * (CANVAS_WIDTH - actualSize * 2) + actualSize,
      y: Math.random() * (CANVAS_HEIGHT - actualSize * 2) + actualSize,
      width: actualSize,
      height: actualSize,
      color: COLORS[Math.floor(Math.random() * COLORS.length)].hex,
      shape,
      rotation: Math.random() * 360,
      opacity: 0.9 + Math.random() * 0.1,
      isTarget,
      size
    };
  }, []);

  // 生成测试任务
  const generateTasks = useCallback((): VisualTask[] => {
    const tasks: VisualTask[] = [];
    let taskId = 1;

    // 目标检测任务 (4道)
    for (let i = 0; i < 4; i++) {
      tasks.push(generateTargetDetectionTask(taskId++));
    }

    // 颜色辨别任务 (3道)
    for (let i = 0; i < 3; i++) {
      tasks.push(generateColorDiscriminationTask(taskId++));
    }

    // 大小比较任务 (3道)
    for (let i = 0; i < 3; i++) {
      tasks.push(generateSizeComparisonTask(taskId++));
    }

    // 空间记忆任务 (2道)
    for (let i = 0; i < 2; i++) {
      tasks.push(generateSpatialMemoryTask(taskId++));
    }

    // 形状识别任务 (2道)
    for (let i = 0; i < 2; i++) {
      tasks.push(generateShapeRecognitionTask(taskId++));
    }

    // 图案匹配任务 (1道)
    tasks.push(generatePatternMatchingTask(taskId++));

    return tasks.sort(() => Math.random() - 0.5);
  }, [generateRandomElement]);

  const generateTargetDetectionTask = (id: number): VisualTask => {
    const targetColor = COLORS[Math.floor(Math.random() * COLORS.length)];
    const targetShape = ['circle', 'square', 'triangle'][Math.floor(Math.random() * 3)];
    
    const elements: VisualElement[] = [];
    const targets: number[] = [];
    const numElements = 12 + Math.floor(Math.random() * 8);
    const numTargets = 2 + Math.floor(Math.random() * 2);

    // 生成目标元素
    for (let i = 0; i < numTargets; i++) {
      const element = generateRandomElement(i, true);
      element.color = targetColor.hex;
      element.shape = targetShape as VisualElement['shape'];
      elements.push(element);
      targets.push(i);
    }

    // 生成干扰元素
    for (let i = numTargets; i < numElements; i++) {
      const element = generateRandomElement(i);
      // 确保不是目标
      if (element.color === targetColor.hex && element.shape === targetShape) {
        element.color = COLORS.filter(c => c.hex !== targetColor.hex)[Math.floor(Math.random() * (COLORS.length - 1))].hex;
      }
      elements.push(element);
    }

    const shapeNames = { circle: '圆形', square: '正方形', triangle: '三角形' };

    return {
      id,
      type: 'target_detection',
      instruction: `找出所有${shapeNames[targetShape as keyof typeof shapeNames]}且颜色为${targetColor.name}的图形`,
      elements,
      targets,
      timeLimit: 15,
      difficulty: numTargets > 2 ? 'hard' : 'medium',
      minTargets: numTargets,
      maxTargets: numTargets
    };
  };

  const generateColorDiscriminationTask = (id: number): VisualTask => {
    const elements: VisualElement[] = [];
    const targets: number[] = [];
    const numElements = 8 + Math.floor(Math.random() * 4);
    const baseColor = COLORS[Math.floor(Math.random() * COLORS.length)];
    const differentColor = COLORS.filter(c => c.hex !== baseColor.hex)[Math.floor(Math.random() * (COLORS.length - 1))];

    // 生成大部分相同颜色的元素
    for (let i = 0; i < numElements; i++) {
      const element = generateRandomElement(i);
      element.shape = 'circle'; // 统一形状，专注颜色
      
      if (i === 0) { // 第一个是不同颜色的目标
        element.color = differentColor.hex;
        element.isTarget = true;
        targets.push(i);
      } else {
        element.color = baseColor.hex;
      }
      
      elements.push(element);
    }

    return {
      id,
      type: 'color_discrimination',
      instruction: `找出颜色不同的圆形（大部分是${baseColor.name}）`,
      elements,
      targets,
      timeLimit: 12,
      difficulty: 'medium',
      minTargets: 1,
      maxTargets: 1
    };
  };

  const generateSizeComparisonTask = (id: number): VisualTask => {
    const elements: VisualElement[] = [];
    const targets: number[] = [];
    const shapes = ['circle', 'square'];
    const shape = shapes[Math.floor(Math.random() * shapes.length)] as VisualElement['shape'];
    const color = COLORS[Math.floor(Math.random() * COLORS.length)];
    
    // 生成不同大小的元素
    const sizes = [20, 25, 30, 35, 40, 45];
    const targetSize = Math.max(...sizes);
    
    for (let i = 0; i < 6; i++) {
      const element = generateRandomElement(i);
      element.shape = shape;
      element.color = color.hex;
      element.width = sizes[i];
      element.height = sizes[i];
      
      if (sizes[i] === targetSize) {
        element.isTarget = true;
        targets.push(i);
      }
      
      elements.push(element);
    }

    return {
      id,
      type: 'size_comparison',
      instruction: '找出最大的图形',
      elements,
      targets,
      timeLimit: 10,
      difficulty: 'easy',
      minTargets: 1,
      maxTargets: 1
    };
  };

  const generateSpatialMemoryTask = (id: number): VisualTask => {
    const elements: VisualElement[] = [];
    const targets: number[] = [];
    const numElements = 6 + Math.floor(Math.random() * 2);
    const numTargets = 2 + Math.floor(Math.random() * 2);
    
    // 生成随机位置的元素
    for (let i = 0; i < numElements; i++) {
      const element = generateRandomElement(i);
      element.color = COLORS[0].hex; // 统一颜色
      element.shape = 'circle'; // 统一形状
      
      if (i < numTargets) {
        element.isTarget = true;
        targets.push(i);
      }
      
      elements.push(element);
    }

    return {
      id,
      type: 'spatial_memory',
      instruction: '记住高亮显示的位置，然后点击它们',
      elements,
      targets,
      timeLimit: 15,
      difficulty: numTargets > 2 ? 'hard' : 'medium',
      minTargets: numTargets,
      maxTargets: numTargets,
      showMemoryPhase: true,
      memoryTime: 3
    };
  };

  const generateShapeRecognitionTask = (id: number): VisualTask => {
    const targetShape = ['star', 'hexagon', 'diamond'][Math.floor(Math.random() * 3)] as VisualElement['shape'];
    const elements: VisualElement[] = [];
    const targets: number[] = [];
    const numElements = 10 + Math.floor(Math.random() * 5);
    const numTargets = 2 + Math.floor(Math.random() * 2); // 2-3个目标
    
    // 生成干扰元素
    for (let i = 0; i < numElements - numTargets; i++) {
      const element = generateRandomElement(i);
      // 确保不是目标形状
      const otherShapes = ['circle', 'square', 'triangle'].filter(s => s !== targetShape);
      element.shape = otherShapes[Math.floor(Math.random() * otherShapes.length)] as VisualElement['shape'];
      element.color = COLORS[Math.floor(Math.random() * COLORS.length)].hex;
      elements.push(element);
    }
    
    // 生成目标元素
    for (let i = 0; i < numTargets; i++) {
      const element = generateRandomElement(numElements - numTargets + i);
      element.shape = targetShape;
      element.color = COLORS[Math.floor(Math.random() * COLORS.length)].hex;
      element.isTarget = true;
      targets.push(numElements - numTargets + i);
      elements.push(element);
    }

    // 打乱元素顺序
    for (let i = elements.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [elements[i], elements[j]] = [elements[j], elements[i]];
      // 更新目标索引
      if (targets.includes(i)) {
        targets[targets.indexOf(i)] = j;
      } else if (targets.includes(j)) {
        targets[targets.indexOf(j)] = i;
      }
    }
    
    // 重新分配ID
    elements.forEach((element, index) => {
      element.id = index;
    });
    
    // 更新目标数组
    const newTargets: number[] = [];
    elements.forEach((element, index) => {
      if (element.isTarget) {
        newTargets.push(index);
      }
    });

    const shapeNames = { star: '星形', hexagon: '六边形', diamond: '菱形' };

    return {
      id,
      type: 'shape_recognition',
      instruction: `找出所有${shapeNames[targetShape as keyof typeof shapeNames]}`,
      elements,
      targets: newTargets,
      timeLimit: 15,
      difficulty: 'medium',
      minTargets: numTargets,
      maxTargets: numTargets
    };
  };

  const generatePatternMatchingTask = (id: number): VisualTask => {
    const elements: VisualElement[] = [];
    const targets: number[] = [];
    
    // 创建对称模式：左侧放置基础图形，右侧放置对称图形和干扰图形
    const baseElements = 3;
    const centerX = CANVAS_WIDTH / 2;
    
    // 左侧基础图形
    for (let i = 0; i < baseElements; i++) {
      const element = generateRandomElement(i);
      element.x = 100 + i * 60; // 左侧排列
      element.y = 150 + (i % 2) * 100; // 错落排列
      element.color = COLORS[i % COLORS.length].hex;
      element.shape = (['circle', 'square', 'triangle'] as VisualElement['shape'][])[i % 3];
      element.size = 'medium';
      element.width = 35;
      element.height = 35;
      elements.push(element);
    }
    
    // 右侧对称图形（这些是目标）
    for (let i = 0; i < baseElements; i++) {
      const baseElement = elements[i];
      const symmetric = { ...baseElement };
      symmetric.id = baseElements + i;
      symmetric.x = CANVAS_WIDTH - baseElement.x; // 水平对称
      symmetric.y = baseElement.y; // 保持相同高度
      symmetric.isTarget = true;
      elements.push(symmetric);
      targets.push(baseElements + i);
    }
    
    // 右侧干扰图形（不对称的）
    const distractorCount = 2;
    for (let i = 0; i < distractorCount; i++) {
      const distractor = generateRandomElement(baseElements * 2 + i);
      distractor.x = centerX + 50 + i * 80;
      distractor.y = 250;
      // 确保颜色和形状与左侧不匹配
      distractor.color = COLORS[(baseElements + i) % COLORS.length].hex;
      distractor.shape = (['star', 'hexagon'] as VisualElement['shape'][])[i % 2];
      distractor.size = 'medium';
      distractor.width = 35;
      distractor.height = 35;
      elements.push(distractor);
    }

    return {
      id,
      type: 'pattern_matching',
      instruction: '找出右半边与左半边对称的图形',
      elements,
      targets,
      timeLimit: 20,
      difficulty: 'hard',
      minTargets: baseElements,
      maxTargets: baseElements
    };
  };

  // 绘制图形到Canvas
  const drawElement = (ctx: CanvasRenderingContext2D, element: VisualElement, showAsTarget = false, showAsCorrect = false) => {
    ctx.save();
    ctx.translate(element.x, element.y);
    ctx.rotate((element.rotation * Math.PI) / 180);
    ctx.globalAlpha = element.opacity;
    
    // 根据不同状态设置样式
    if (showAsCorrect) {
      // 显示正确答案：绿色高亮
      ctx.fillStyle = element.color;
      ctx.strokeStyle = '#22c55e'; // 绿色边框
      ctx.lineWidth = 6;
    } else if (showAsTarget && isMemoryPhase) {
      // 记忆阶段：黄色高亮
      ctx.fillStyle = '#fbbf24';
      ctx.strokeStyle = '#f59e0b';
      ctx.lineWidth = 4;
    } else if (selectedElements.includes(element.id)) {
      // 用户选择：黑色边框
      ctx.fillStyle = element.color;
      ctx.strokeStyle = '#000000';
      ctx.lineWidth = 3;
    } else {
      // 普通状态
      ctx.fillStyle = element.color;
      ctx.strokeStyle = element.color;
      ctx.lineWidth = 1;
    }

    const size = element.width;
    
    switch (element.shape) {
      case 'circle':
        ctx.beginPath();
        ctx.arc(0, 0, size / 2, 0, 2 * Math.PI);
        ctx.fill();
        if (selectedElements.includes(element.id) || (showAsTarget && isMemoryPhase) || showAsCorrect) ctx.stroke();
        break;
        
      case 'square':
        ctx.fillRect(-size / 2, -size / 2, size, size);
        if (selectedElements.includes(element.id) || (showAsTarget && isMemoryPhase) || showAsCorrect) {
          ctx.strokeRect(-size / 2, -size / 2, size, size);
        }
        break;
        
      case 'triangle':
        ctx.beginPath();
        ctx.moveTo(0, -size / 2);
        ctx.lineTo(-size / 2, size / 2);
        ctx.lineTo(size / 2, size / 2);
        ctx.closePath();
        ctx.fill();
        if (selectedElements.includes(element.id) || (showAsTarget && isMemoryPhase) || showAsCorrect) ctx.stroke();
        break;
        
      case 'diamond':
        ctx.beginPath();
        ctx.moveTo(0, -size / 2); // 顶点
        ctx.lineTo(size / 2 * 0.8, 0); // 右点
        ctx.lineTo(0, size / 2); // 底点
        ctx.lineTo(-size / 2 * 0.8, 0); // 左点
        ctx.closePath();
        ctx.fill();
        if (selectedElements.includes(element.id) || (showAsTarget && isMemoryPhase) || showAsCorrect) ctx.stroke();
        break;
        
      case 'star':
        const spikes = 5;
        const outerRadius = size / 2;
        const innerRadius = outerRadius * 0.4;
        
        ctx.beginPath();
        for (let i = 0; i < spikes * 2; i++) {
          const radius = i % 2 === 0 ? outerRadius : innerRadius;
          const angle = (i * Math.PI) / spikes;
          const x = Math.cos(angle) * radius;
          const y = Math.sin(angle) * radius;
          
          if (i === 0) ctx.moveTo(x, y);
          else ctx.lineTo(x, y);
        }
        ctx.closePath();
        ctx.fill();
        if (selectedElements.includes(element.id) || (showAsTarget && isMemoryPhase) || showAsCorrect) ctx.stroke();
        break;
        
      case 'hexagon':
        ctx.beginPath();
        for (let i = 0; i < 6; i++) {
          const angle = (i * Math.PI) / 3;
          const x = Math.cos(angle) * (size / 2);
          const y = Math.sin(angle) * (size / 2);
          
          if (i === 0) ctx.moveTo(x, y);
          else ctx.lineTo(x, y);
        }
        ctx.closePath();
        ctx.fill();
        if (selectedElements.includes(element.id) || (showAsTarget && isMemoryPhase) || showAsCorrect) ctx.stroke();
        break;
    }
    
    ctx.restore();
  };

  // 绘制Canvas
  const drawCanvas = useCallback(() => {
    const canvas = canvasRef.current;
    if (!canvas || tasks.length === 0) return;
    
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    
    // 清空画布
    ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
    
    // 绘制背景
    ctx.fillStyle = '#f8fafc';
    ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
    
    // 绘制边框
    ctx.strokeStyle = '#e2e8f0';
    ctx.lineWidth = 2;
    ctx.strokeRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
    
    const task = tasks[currentTask];
    
    // 对于对称图形任务，绘制中线辅助
    if (task.type === 'pattern_matching') {
      ctx.strokeStyle = '#cbd5e1';
      ctx.lineWidth = 2;
      ctx.setLineDash([5, 5]);
      ctx.beginPath();
      ctx.moveTo(CANVAS_WIDTH / 2, 0);
      ctx.lineTo(CANVAS_WIDTH / 2, CANVAS_HEIGHT);
      ctx.stroke();
      ctx.setLineDash([]); // 重置虚线
    }
    
    // 绘制元素
    task.elements.forEach(element => {
      const showAsTarget = task.type === 'spatial_memory' && element.isTarget;
      const showAsCorrect = showCorrectAnswers && element.isTarget;
      drawElement(ctx, element, showAsTarget, showAsCorrect);
    });
  }, [tasks, currentTask, selectedElements, isMemoryPhase, showCorrectAnswers]);

  // 处理Canvas点击
  const handleCanvasClick = (event: React.MouseEvent<HTMLCanvasElement>) => {
    if (isMemoryPhase || showFeedback) return; // 记忆阶段和反馈阶段不能点击
    
    const canvas = canvasRef.current;
    if (!canvas || tasks.length === 0) return;
    
    const rect = canvas.getBoundingClientRect();
    const scaleX = canvas.width / rect.width;
    const scaleY = canvas.height / rect.height;
    const x = (event.clientX - rect.left) * scaleX;
    const y = (event.clientY - rect.top) * scaleY;
    
    const task = tasks[currentTask];
    
    // 检查点击的元素（增加点击容错）
    for (const element of task.elements) {
      const dx = x - element.x;
      const dy = y - element.y;
      const distance = Math.sqrt(dx * dx + dy * dy);
      
      if (distance <= element.width / 2 + 10) { // 增加点击容错
        handleElementClick(element.id);
        break;
      }
    }
  };

  const handleElementClick = (elementId: number) => {
    setSelectedElements(prev => {
      if (prev.includes(elementId)) {
        return prev.filter(id => id !== elementId);
      } else {
        return [...prev, elementId];
      }
    });
  };

  const handleSubmit = () => {
    if (tasks.length === 0) return;
    
    const task = tasks[currentTask];
    const reactionTime = Date.now() - taskStartTime;
    
    // 计算准确率
    const correctSelections = selectedElements.filter(id => task.targets.includes(id));
    const incorrectSelections = selectedElements.filter(id => !task.targets.includes(id));
    
    const accuracy = task.targets.length > 0 ? 
      correctSelections.length / task.targets.length : 1;
    
    const isCorrect = correctSelections.length === task.targets.length && incorrectSelections.length === 0;
    
    setResponses(prev => [...prev, {
      correct: isCorrect,
      time: reactionTime,
      accuracy: accuracy * 100
    }]);
    
    if (isCorrect) {
      setScore(prev => prev + 1);
    } else {
      // 如果答错了，显示正确答案
      setShowCorrectAnswers(true);
    }
    
    // 显示反馈
    setFeedbackCorrect(isCorrect);
    setShowFeedback(true);
    
    setTimeout(() => {
      setShowFeedback(false);
      setShowCorrectAnswers(false);
      setSelectedElements([]);
      
      if (currentTask < tasks.length - 1) {
        setCurrentTask(prev => prev + 1);
        setTaskStartTime(Date.now());
      } else {
        setStage('complete');
      }
    }, isCorrect ? 1500 : 3000); // 错误答案显示更长时间
  };

  // 开始记忆阶段
  const startMemoryPhase = () => {
    const task = tasks[currentTask];
    if (task.showMemoryPhase) {
      setIsMemoryPhase(true);
      setTimeLeft(task.memoryTime || 3);
      setTimeout(() => {
        setIsMemoryPhase(false);
        setTimeLeft(task.timeLimit);
        setTaskStartTime(Date.now());
      }, (task.memoryTime || 3) * 1000);
    } else {
      setTimeLeft(task.timeLimit);
      setTaskStartTime(Date.now());
    }
  };

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0 && !isMemoryPhase) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            handleSubmit();
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } else if (isMemoryPhase && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => prev - 1);
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft, tasks, currentTask, isMemoryPhase]);

  useEffect(() => {
    drawCanvas();
  }, [drawCanvas]);

  useEffect(() => {
    if (stage === 'test' && tasks.length > 0) {
      startMemoryPhase();
    }
  }, [currentTask, stage]);

  const handleStartTest = () => {
    const generatedTasks = generateTasks();
    setTasks(generatedTasks);
    setStage('test');
    setStartTime(Date.now());
  };

  const resetTest = () => {
    setStage('instructions');
    setCurrentTask(0);
    setTasks([]);
    setSelectedElements([]);
    setResponses([]);
    setScore(0);
    setShowFeedback(false);
    setIsMemoryPhase(false);
    setShowCorrectAnswers(false);
  };

  const handleComplete = () => {
    const totalTasks = tasks.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalTasks) * 100);
    const timeUsed = Math.round((Date.now() - startTime) / 1000);
    const averageReactionTime = responses.reduce((sum, r) => sum + r.time, 0) / responses.length;

    // 按任务类型统计
    const typeStats: { [key: string]: { correct: number; total: number; avgTime: number } } = {};
    
    tasks.forEach((task, index) => {
      const type = task.type;
      if (!typeStats[type]) {
        typeStats[type] = { correct: 0, total: 0, avgTime: 0 };
      }
      typeStats[type].total++;
      if (responses[index]?.correct) {
        typeStats[type].correct++;
      }
      typeStats[type].avgTime += responses[index]?.time || 0;
    });

    // 计算平均时间
    Object.keys(typeStats).forEach(type => {
      typeStats[type].avgTime = typeStats[type].avgTime / typeStats[type].total;
    });

    const result: TestResult = {
      id: Date.now().toString(),
      testType: '视觉感知测试',
      score: accuracy,
      details: `准确率 ${accuracy}%, 平均反应时间 ${Math.round(averageReactionTime)}ms, 完成 ${totalTasks} 题`,
      timestamp: new Date()
    };

    onComplete(result);
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-teal-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-teal-600 to-cyan-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Eye className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">视觉感知测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您的视觉识别和空间感知能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-teal-50 to-cyan-50 rounded-xl p-6 border border-teal-100">
              <h3 className="font-semibold text-teal-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>观察画布中的各种视觉元素</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>根据指令识别目标图形、颜色或模式</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>点击选择符合要求的视觉元素</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-teal-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>点击"提交答案"按钮完成每道题</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-amber-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">!</span>
                  <p className="text-amber-700 font-medium">答错时会用绿色边框显示正确答案</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
              <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200">
                <h4 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
                  <Target className="w-4 h-4" />
                  目标检测
                </h4>
                <p className="text-sm text-blue-700">快速找出指定的视觉目标</p>
              </div>
              <div className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 border border-purple-200">
                <h4 className="font-semibold text-purple-800 mb-2 flex items-center gap-2">
                  <Zap className="w-4 h-4" />
                  快速识别
                </h4>
                <p className="text-sm text-purple-700">测试视觉处理速度和准确性</p>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-teal-50 to-teal-100 rounded-xl border border-teal-200">
                <div className="text-2xl font-bold text-teal-600 mb-1">6</div>
                <div className="text-sm text-teal-700">任务类型</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-cyan-50 to-cyan-100 rounded-xl border border-cyan-200">
                <div className="text-2xl font-bold text-cyan-600 mb-1">15</div>
                <div className="text-sm text-cyan-700">动态任务</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-teal-50 to-cyan-50 rounded-xl border border-teal-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">限时</div>
                <div className="text-sm text-slate-700">视觉挑战</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test' && tasks.length > 0) {
    const task = tasks[currentTask];
    const progress = ((currentTask + 1) / tasks.length) * 100;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-teal-100 text-teal-700 border-teal-300">
              任务 {currentTask + 1} / {tasks.length}
            </Badge>
            <Badge variant="outline" className={`${
              task.type === 'target_detection' ? 'bg-blue-100 text-blue-700 border-blue-300' :
              task.type === 'color_discrimination' ? 'bg-green-100 text-green-700 border-green-300' :
              task.type === 'size_comparison' ? 'bg-purple-100 text-purple-700 border-purple-300' :
              task.type === 'spatial_memory' ? 'bg-orange-100 text-orange-700 border-orange-300' :
              task.type === 'shape_recognition' ? 'bg-pink-100 text-pink-700 border-pink-300' :
              'bg-indigo-100 text-indigo-700 border-indigo-300'
            }`}>
              {task.type === 'target_detection' ? '目标检测' :
               task.type === 'color_discrimination' ? '颜色辨别' :
               task.type === 'size_comparison' ? '大小比较' :
               task.type === 'spatial_memory' ? '空间记忆' :
               task.type === 'shape_recognition' ? '形状识别' : '图案匹配'}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score}</span>
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-slate-500" />
            <span className={`font-mono text-lg font-bold ${timeLeft <= 5 ? 'text-red-500' : 'text-slate-700'}`}>
              {timeLeft}s
            </span>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 任务指令 */}
        <Card className="bg-gradient-to-r from-slate-50 to-gray-50 border-slate-200">
          <CardHeader>
            <CardTitle className="text-lg text-slate-800 text-center">
              {isMemoryPhase ? '记住高亮的元素...' : task.instruction}
            </CardTitle>
          </CardHeader>
        </Card>

        {/* 画布区域 */}
        <Card className="bg-white/90 backdrop-blur-sm border-teal-200 shadow-lg">
          <CardContent className="p-6">
            <div className="flex flex-col items-center gap-4">
              <canvas
                ref={canvasRef}
                width={CANVAS_WIDTH}
                height={CANVAS_HEIGHT}
                onClick={handleCanvasClick}
                className={`border-2 border-slate-300 rounded-lg transition-colors ${
                  isMemoryPhase || showFeedback ? 'cursor-not-allowed' : 'cursor-crosshair hover:border-teal-400'
                }`}
                style={{ maxWidth: '100%', height: 'auto' }}
              />
              
              <div className="flex items-center justify-between w-full max-w-md">
                <div className="text-sm text-slate-600">
                  已选择: {selectedElements.length} / {task.maxTargets}
                </div>
                
                {!isMemoryPhase && !showFeedback && (
                  <Button 
                    onClick={handleSubmit}
                    disabled={selectedElements.length === 0}
                    className="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0"
                  >
                    提交答案
                  </Button>
                )}
              </div>

              {/* 画布下方的反馈区域 */}
              <AnimatePresence>
                {showFeedback && (
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -20 }}
                    className="w-full max-w-md"
                  >
                    <Card className={`p-4 ${feedbackCorrect ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'}`}>
                      <div className="flex items-center justify-center space-x-4">
                        <div className={`text-2xl ${feedbackCorrect ? 'text-green-600' : 'text-red-600'}`}>
                          {feedbackCorrect ? '✓' : '✗'}
                        </div>
                        <div className="flex-1 text-center">
                          <div className={`font-semibold ${feedbackCorrect ? 'text-green-800' : 'text-red-800'}`}>
                            {feedbackCorrect ? '回答正确！' : '回答错误'}
                          </div>
                          {!feedbackCorrect && (
                            <div className="text-sm text-red-700 mt-1">
                              <p>正确答案已用<span className="font-semibold text-green-600">绿色边框</span>标出</p>
                            </div>
                          )}
                        </div>
                      </div>
                    </Card>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          </CardContent>
        </Card>


      </motion.div>
    );
  }

  if (stage === 'complete') {
    const totalTasks = tasks.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalTasks) * 100);
    const averageReactionTime = responses.reduce((sum, r) => sum + r.time, 0) / responses.length;

    const getRating = () => {
      if (accuracy >= 90) return { text: '视觉大师', color: 'text-yellow-500' };
      if (accuracy >= 80) return { text: '优秀', color: 'text-green-500' };
      if (accuracy >= 70) return { text: '良好', color: 'text-blue-500' };
      if (accuracy >= 60) return { text: '一般', color: 'text-gray-500' };
      return { text: '需要提高', color: 'text-orange-500' };
    };

    const rating = getRating();

    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto space-y-6"
      >
        <Card>
          <CardHeader className="text-center">
            <CardTitle className="flex items-center justify-center gap-2">
              <CheckCircle className="w-6 h-6 text-teal-500" />
              测试完成！
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center space-y-4">
              <div className="text-6xl font-bold text-primary">
                {accuracy}
              </div>
              <div className={`text-xl font-semibold ${rating.color}`}>
                {rating.text}
              </div>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
                <div className="text-2xl font-bold text-green-600">{correctAnswers}</div>
                <div className="text-sm text-muted-foreground">正确</div>
              </div>
              <div className="text-center p-4 bg-red-50 dark:bg-red-950 rounded-lg">
                <div className="text-2xl font-bold text-red-600">{totalTasks - correctAnswers}</div>
                <div className="text-sm text-muted-foreground">错误</div>
              </div>
              <div className="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
                <div className="text-2xl font-bold text-blue-600">{accuracy}%</div>
                <div className="text-sm text-muted-foreground">准确率</div>
              </div>
              <div className="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg">
                <div className="text-2xl font-bold text-purple-600">{Math.round(averageReactionTime)}ms</div>
                <div className="text-sm text-muted-foreground">平均反应时间</div>
              </div>
            </div>

            <div className="space-y-2">
              <h3 className="font-semibold">详细分析</h3>
              <div className="text-sm text-muted-foreground space-y-1">
                <p>• 完成了 {totalTasks} 道视觉感知测试题</p>
                <p>• 涵盖目标检测、颜色辨别、大小比较等6个能力维度</p>
                <p>• 平均反应时间：{Math.round(averageReactionTime)}毫秒</p>
                {accuracy >= 85 && (
                  <p className="text-green-600">• 优秀：视觉感知能力很强，反应敏捷</p>
                )}
                {accuracy < 70 && (
                  <p className="text-orange-600">• 建议：加强视觉注意力和图形识别训练</p>
                )}
              </div>
            </div>

            <div className="flex gap-4">
              <Button 
                onClick={resetTest} 
                variant="outline" 
                className="flex-1 border-2 border-slate-300 hover:border-slate-400 hover:bg-slate-50 text-slate-700 hover:text-slate-800 shadow-sm hover:shadow-md transition-all duration-300"
              >
                <RotateCcw className="w-4 h-4 mr-2" />
                重新测试
              </Button>
              <Button 
                onClick={handleComplete} 
                className="flex-1 bg-gradient-to-r from-teal-500 to-cyan-600 hover:from-teal-600 hover:to-cyan-700 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0"
              >
                <CheckCircle className="w-4 h-4 mr-2" />
                保存结果
              </Button>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}